/*
 * @description:
 * @Author: lal
 * @Date: 2021-04-26 16:16:31
 * @LastEditors: lal
 * @LastEditTime: 2021-04-26 16:23:44
 */
/*
 * @lc app=leetcode.cn id=21 lang=javascript
 *
 * [21] 合并两个有序链表
 */

/**
 * head 创建新的链表节点， dummy(假) 保存新链表的头节点
 * 若l1与l2都未遍历完毕，将较小的节点接在新链表上
 * 若一方遍历完毕则将另一方接上
 * 返回dummy链表节点的next
 *
 */
// @lc code=start
/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} l1
 * @param {ListNode} l2
 * @return {ListNode}
 */
var mergeTwoLists = function (l1, l2) {
  let head = new ListNode() //合并两个有序链表
  let dummy = head

  while (l1 && l2) {
    if (l1.val < l2.val) {
      head.next = l1
      l1 = l1.next
    } else {
      head.next = l2
      l2 = l2.next
    }
    head = head.next
  }
  if (l1) head.next = l1
  if (l2) head.next = l2

  return dummy.next
}
// @lc code=end
